package com.florent3.shapeofview.sample.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import com.florent3.shapeofview.sample.ResourceTable;
import com.github.florent37.shapeofview.shapes.RoundRectView;

/**
 * 绘线和动画效果
 *
 * @since 2021-07-26
 */
public class ShapeOfViewAnimationAbilitySlice extends AbilitySlice {
    private RoundRectView roundRect;
    private AnimatorValue value;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_shape_of_view_animation);
        initView();
    }

    private void initView() {
        roundRect = (RoundRectView) findComponentById(ResourceTable.Id_roundRect);
        if (roundRect != null) {
            value = new AnimatorValue();
            value.setDuration(800L);  //动画持续时间
            value.setLoopedCount(Animator.INFINITE);  //动画无限次重复
            value.setCurveType(Animator.CurveType.LINEAR);
            value.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
                @Override
                public void onUpdate(AnimatorValue animatorValue, float v) {
                    roundRect.setBottomLeftRadius(getAnimatedValue(v, 200f, -200f));
                }
            });
            value.start();

        }
    }

    /**
     * get the animated value with fraction and values
     *
     * @param fraction 0~1
     * @param values float array
     * @return float animated value
     */
    public static float getAnimatedValue(float fraction, float... values) {
        if (values == null || values.length == 0) {
            return 0;
        }
        if (values.length == 1) {
            return values[0] * fraction;
        } else {
            if (fraction == 1) {
                return values[values.length - 1];
            }
            float oneFraction = 1f / (values.length - 1);
            float offFraction = 0;
            for (int i = 0; i < values.length - 1; i++) {
                if (offFraction + oneFraction >= fraction) {
                    return values[i] + (fraction - offFraction) * (values.length - 1) * (values[i + 1] - values[i]);
                }
                offFraction += oneFraction;
            }
        }
        return 0;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
